package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.util.JSONUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.UserType;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.market.MarketBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.market.back.MarketBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.market.back.StockIndustryData;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.market.back.StockIndustryList;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.market.vo.MarketVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.market.vo.StockIndustryQryForm;
import com.cloudbroker.bcs.platform.ltb.common.marketUtil.bean.AccessToken;
import com.cloudbroker.bcs.platform.ltb.common.marketUtil.util.HttpClientUtil;
import com.cloudbroker.bcs.platform.ltb.common.marketUtil.util.JacksonUtils;
import com.cloudbroker.bcs.platform.ltb.middle.entity.Market;
import com.cloudbroker.bcs.platform.ltb.middle.service.MarketService;
import com.cloudbroker.bcs.platform.ltb.middle.util.MarketTokenUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by daibd19671 on 2016/8/20.
 */
@Service
public class MarketBizServiceImpl implements MarketBizService {

    private Logger logger = Logger.getLogger(com.cloudbroker.bcs.platform.ltb.middle.service.impl.MarketServiceImpl.class);

    public static final String  IFS_COMPANY_ID = "91032";
    public static final String  IFS_SENDERCOM_ID = "91032";
    @Resource
    private MarketService marketService;

    @Override
    public MarketBackVo getMarketToken(MarketVo form) {
        Market market = null;
        if(form.getUser()!=null && form.getUser().getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){
            market = new Market(IFS_COMPANY_ID, IFS_SENDERCOM_ID);
        }else{
            market = new Market(form.getCompany_id(), form.getSendercomp_id());
        }
        String token = MarketTokenUtil.getMarketToken(market);
        if (StringUtils.isEmpty(token)) {
            Market temp = marketService.getMarketToken(market);
            if (temp == null) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.MARKET_TOKEN, MarketBackVo.class);
            }
            AccessToken accesstoken = null;
            try {
                Map<String, String> token_map = new HashMap<>();
                token_map.put("grant_type", "client_credentials");// 客户端凭证模式时，必须为“client_credentials”；
                token_map.put("client_id", temp.getApp_key());
                String tokenResult = HttpClientUtil.sendPost(ConfigUtil.getString("func_market_address"), token_map,
                        HttpClientUtil.CHARSET, HttpClientUtil.CHARSET, null,HttpClientUtil.Base64(temp.getApp_key(), temp.getApp_secret(), "Basic "),
                        "获取公共令牌");
                accesstoken = JacksonUtils.json2Object(tokenResult, AccessToken.class);
            } catch (Exception e) {
                e.printStackTrace();
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.MARKET_TOKEN_CONNECT_ERR, MarketBackVo.class);
            }
//            JSONObject obj = this.marketJSON(temp);
            if (accesstoken == null) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.MARKET_TOKEN_RESULT_ERR, MarketBackVo.class);
            }
            token = accesstoken.getAccess_token();
            if (token == null || StringUtils.isEmpty(token)) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.MARKET_TOKEN_RESULT_ERR, MarketBackVo.class);
            }
            temp.setMarket_token(token);
            //刷新缓存
            MarketTokenUtil.setMarketToken(temp);
            marketService.udpateToken(temp);
        }
        MarketBackVo back = new MarketBackVo();
        back.setMarket_token(token);
        return VOUtil.setSuccessResult(back);
    }


    /**
     * 获取行情token
     *
     * @return
     */
    private JSONObject marketJSON(Market market) {
        CloseableHttpResponse response=null;
        InputStream instream =null;
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            //加载证书文件
            instream =this.getClass().getClassLoader().getResourceAsStream("hscloud.store");
            trustStore.load(instream, "Hundsun123".toCharArray());
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            HttpPost httppost = new HttpPost(ConfigUtil.getString("func_market_address"));
            //设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200).setConnectTimeout(200).build();
            httppost.setConfig(requestConfig);
            String str = market.getApp_key() + ":" + market.getApp_secret();
            String authorization = "Basic " + Base64Utils.encodeToString(str.getBytes());
            httppost.setHeader("Authorization", authorization);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("grant_type", "client_credentials"));
            formparams.add(new BasicNameValuePair("client_id", market.getApp_key()));
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            response = httpClient.execute(httppost);
            HttpEntity entity = response.getEntity();
            JSONObject obj = JSONUtil.toJsonObject(EntityUtils.toString(entity));
            System.out.println(obj.toString());
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if(instream!=null){
                try {
                    instream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    instream = null;
                }
            }
            if(response!=null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    response = null;
                }
            }
        }

    }


    public StockIndustryList getStockIndustry(StockIndustryQryForm form){
        InputStream instream = null;
        try {
            StockIndustryList stockIndustryList = new StockIndustryList();
            List<StockIndustryData> dataList = new ArrayList<>();
            CloseableHttpResponse response = null;
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            //加载证书文件
            instream = MarketBizServiceImpl.class.getClassLoader().getResourceAsStream("hscloud.store");
            trustStore.load(instream, "Hundsun123".toCharArray());
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();

            List<String> codeList= JSONArray.parseArray(form.getProd_code(),String.class);
            for (String code :codeList) {
                String host = new URL(ConfigUtil.getString("func_market_address")).getHost();
                String url ="https://" + host +
                        "/quote/v1/block/query";
                HttpGet httpGet = new HttpGet(url);
                RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200).setConnectTimeout(200).build();//设置请求和传输超时时间
                httpGet.setConfig(requestConfig);
                httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
                Map<String, String> param = new HashMap<>();
                param.put("access_token",form.getAccess_token());
                param.put("prod_code",code);
                JSONObject obj = JSONUtil.toJsonObject( HttpClientUtil.sendGet(url, param, HttpClientUtil.CHARSET, null,
                        null, "获取股票行业"));

//                response = httpClient.execute(httpGet);
//                HttpEntity entity = response.getEntity();
//                JSONObject obj = JSONUtil.toJsonObject(EntityUtils.toString(entity));
                if (obj.get("error") != null || obj.get("error_no") != null) {
                    continue;
                }
                JSONObject obj1 = JSONUtil.toJsonObject(obj.get("data"));
                JSONArray jsonArray = JSONUtil.toJsonArray(obj1.get(code));
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONArray jsonArray1 = (JSONArray) jsonArray.get(i);
                    if (jsonArray1.get(2).equals("XBHS.HY")) {
                        StockIndustryData stockIndustryData = new StockIndustryData();
                        stockIndustryData.setProd_code(code);
                        stockIndustryData.setIndustry(jsonArray1.getString(1));
                        dataList.add(stockIndustryData);
                    }

                }
            }
            stockIndustryList.setData_list(dataList);
            return VOUtil.setSuccessResult(stockIndustryList);
        }catch (Exception e) {
            e.printStackTrace();
            return VOUtil.genErrorResult("1",StockIndustryList.class);
        }finally {
            if(instream != null){
                try {
                    instream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
